<template>
  <div class="doctor-patients-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>我的病人</h2>
        <div></div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in statistics" :key="stat.title">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <el-icon class="stat-icon" :class="stat.color">
                <component :is="stat.icon" />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-title">{{ stat.title }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 病人的列表 -->
    <div class="patients-section">
      <div class="section-header">
        <h3>病人列表</h3>
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索病人姓名或手机号"
            prefix-icon="Search"
            style="width: 250px; margin-right: 15px;"
            clearable
          />
          <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px;">
            <el-option label="全部" value="" />
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </div>
      </div>
      
      <el-card class="patients-table-card" shadow="never">
        <el-table :data="filteredPatients" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="病人信息" width="200">
            <template #default="scope">
              <div class="patient-info">
                <el-avatar :size="40" class="patient-avatar">
                  {{ scope.row.patientName?.charAt(0) }}
                </el-avatar>
                <div class="patient-details">
                  <div class="patient-name">{{ scope.row.patientName }}</div>
                  <div class="patient-phone">{{ scope.row.patientPhone }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentDate" label="预约日期" width="120" />
          <el-table-column prop="appointmentTime" label="预约时间" width="100" />
          <el-table-column prop="symptoms" label="症状描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="预约时间" width="160" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="viewPatientDetail(scope.row)">查看详情</el-button>
              <el-button 
                v-if="scope.row.status === 'pending'"
                size="small" 
                type="success" 
                @click="confirmAppointment(scope.row)"
              >
                确认预约
              </el-button>
              <el-button 
                v-if="scope.row.status === 'confirmed'"
                size="small" 
                type="primary" 
                @click="completeAppointment(scope.row)"
              >
                完成就诊
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mockAPI } from '../utils/mockData'

export default {
  name: 'DoctorPatients',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const patients = ref([])
    const searchKeyword = ref('')
    const statusFilter = ref('')
    const statistics = ref([])

    // 获取当前医生信息
    const currentDoctor = ref(null)
    const userStr = localStorage.getItem('user')
    if (userStr) {
      currentDoctor.value = JSON.parse(userStr)
    }

    // 获取病人列表
    const loadPatients = async () => {
      loading.value = true
      try {
        // 获取所有预约，然后筛选出当前医生的病人
        const result = await mockAPI.getAllAppointments()
        if (result.success) {
          const doctorPatients = result.data.filter(appointment => 
            appointment.doctorId === currentDoctor.value?.id
          )
          patients.value = doctorPatients
          updateStatistics()
        }
      } catch (error) {
        ElMessage.error('获取病人列表失败')
        console.error('获取病人列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 更新统计信息
    const updateStatistics = () => {
      const total = patients.value.length
      const pending = patients.value.filter(p => p.status === 'pending').length
      const confirmed = patients.value.filter(p => p.status === 'confirmed').length
      const completed = patients.value.filter(p => p.status === 'completed').length

      statistics.value = [
        {
          title: '总病人数',
          value: total,
          icon: 'User',
          color: 'text-primary'
        },
        {
          title: '待确认',
          value: pending,
          icon: 'Clock',
          color: 'text-warning'
        },
        {
          title: '已确认',
          value: confirmed,
          icon: 'Check',
          color: 'text-success'
        },
        {
          title: '已完成',
          value: completed,
          icon: 'CircleCheck',
          color: 'text-info'
        }
      ]
    }

    // 筛选病人
    const filteredPatients = computed(() => {
      let filtered = patients.value

      // 关键词搜索
      if (searchKeyword.value) {
        filtered = filtered.filter(patient => 
          patient.patientName?.includes(searchKeyword.value) ||
          patient.patientPhone?.includes(searchKeyword.value)
        )
      }

      // 状态筛选
      if (statusFilter.value) {
        filtered = filtered.filter(patient => patient.status === statusFilter.value)
      }

      return filtered
    })

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'confirmed': 'success',
        'completed': 'info',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return textMap[status] || status
    }

    // 查看病人详情
    const viewPatientDetail = (patient) => {
      ElMessage.info(`查看病人 ${patient.patientName} 的详细信息`)
    }

    // 确认预约
    const confirmAppointment = async (patient) => {
      try {
        await ElMessageBox.confirm(`确认预约病人 ${patient.patientName} 吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 更新预约状态
        patient.status = 'confirmed'
        ElMessage.success('预约已确认')
        updateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('确认失败')
        }
      }
    }

    // 完成就诊
    const completeAppointment = async (patient) => {
      try {
        await ElMessageBox.confirm(`确认完成病人 ${patient.patientName} 的就诊吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 更新预约状态
        patient.status = 'completed'
        ElMessage.success('就诊已完成')
        updateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    onMounted(() => {
      loadPatients()
    })

    return {
      loading,
      patients,
      searchKeyword,
      statusFilter,
      statistics,
      filteredPatients,
      getStatusType,
      getStatusText,
      viewPatientDetail,
      confirmAppointment,
      completeAppointment,
      goBack
    }
  }
}
</script>

<style scoped>
.doctor-patients-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  color: white;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.back-btn .el-icon {
  margin-right: 5px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.stats-section {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.stat-card {
  border: none;
  border-radius: 15px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 40px;
  padding: 15px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.patients-section {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.patients-table-card {
  border: none;
  border-radius: 15px;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.patient-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.patient-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.patient-phone {
  font-size: 12px;
  color: #666;
}

.text-primary {
  color: #409EFF;
}

.text-success {
  color: #67C23A;
}

.text-warning {
  color: #E6A23C;
}

.text-info {
  color: #909399;
}

@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 15px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
  }
}
</style> 